﻿using Aspose.Cells;
using Codemonk.Soya;

namespace Codemonk.Excel.Parser
{
    internal class AsposeWorkbookReader : IWorkbookReader
    {
        private Workbook book;

        public int GetSheetCount()
        {
            return book.Worksheets.Count;
        }

        public string GetSheetName(int sheetIndex)
        {
            var sheet = GetSheet(sheetIndex);
            return sheet == null ? null : sheet.Name;
        }

        private Worksheet GetSheet(int sheetIndex)
        {
            int count = GetSheetCount();
            if (count < sheetIndex) return null;
            return book.Worksheets[sheetIndex];
        }

        public int GetRowCount(int sheetIndex)
        {
            var sheet = GetSheet(sheetIndex);
            return sheet == null ? 0 : sheet.Cells.Rows.Count;
        }

        public int GetColumnCount(int sheetIndex)
        {
            var sheet = GetSheet(sheetIndex);
            return sheet == null ? 0 : sheet.Cells.Columns.Count;
        }
        private string GetCellValue(int sheetIndex, int rowIndex, int columnIndex)
        {
            var sheet = GetSheet(sheetIndex);
            return sheet == null ? null : (sheet.Cells[rowIndex, columnIndex].Value + "").Trim();
        }

        public string GetValue(int sheetIndex, int rowIndex, int columnIndex)
        {
            var sheet = GetSheet(sheetIndex);
            if (sheet == null) return null;
            var cell = sheet.Cells[rowIndex, columnIndex];
            if (cell.IsMerged)
            {
                var range = cell.GetMergedRange();
                return GetCellValue(sheetIndex, range.FirstRow, range.FirstColumn);
            }
            return GetCellValue(sheetIndex, rowIndex, columnIndex);
        }

        public string fileName;
        public string FileName
        {
            get { return fileName; }
            set
            {
                fileName = value;
                book = new Workbook(value);
            }
        }
    }
}
